import axios from 'axios'
import store from '@/store/index.js'
import router from '@/router/index.js'
const service = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net'
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 统一添加token
    const token = store.state.user.profile.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    return response.data.result
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      const fullpath = router.currentRoute.value.fullPath
      router.push(`/login?redirect=${fullpath}`)
    }

    return Promise.reject(err)
  }
)

export default function (url, method, data) {
  return service({
    url,
    method,
    [method === 'get' ? 'params' : 'data']: data
  })
}
